<template>
  <div class="cart-page">
    <h2 class="cart-title">购物车</h2>
    <div v-if="cartItems.length === 0" class="cart-empty">您的购物车为空</div>
    <el-table v-else :data="pendingCartItems" class="cart-table" border>
      <el-table-column prop="productImage" label="图片" width="120">
        <template #default="scope">
          <img :src="scope.row.productImage" class="cart-img" />
        </template>
      </el-table-column>
      <el-table-column prop="productName" label="商品名称" min-width="180" />
      <el-table-column prop="unitPrice" label="单价" width="100">
        <template #default="scope">
          ￥{{ scope.row.unitPrice }}
        </template>
      </el-table-column>
      <el-table-column label="数量" width="200">
        <template #default="scope">
          <el-input-number v-model="scope.row.quantity" :min="1" :max="scope.row.stock || 99" @change="val => updateTotal(val, scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="productOrigin" label="产地" width="120" />
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button type="danger" size="small" @click="removeItem(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="cartItems.length > 0" class="cart-footer">
      <div class="cart-total">总价：<span>￥{{ totalPrice }}</span></div>
      <el-button type="primary" size="large" class="checkout-btn" @click="checkout">去结算</el-button>
    </div>
    <el-dialog v-model="showDialog" title="确认订单" width="600px">
      <el-table :data="pendingCartItems" border>
        <el-table-column prop="imageUrl" label="图片" width="80">
          <template #default="scope">
            <img :src="scope.row.productImage" style="width:60px;height:60px;object-fit:cover;border-radius:6px;" />
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" min-width="120" />
        <el-table-column prop="unitPrice" label="单价" width="80">
          <template #default="scope">￥{{ scope.row.unitPrice }}</template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="60" />
        <el-table-column prop="productOrigin" label="产地" width="80" />
      </el-table>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmOrder">确认下单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import {ElMessage, ElMessageBox, ElNotification} from 'element-plus'
import axios from 'axios'

const cartItems = ref([])
// 只显示待支付（status === 1）的项
const pendingCartItems = computed(() => cartItems.value.filter(item => item.status === 1))
const showDialog = ref(false)

onMounted(() => {
  fetchCartList()
})

function fetchCartList() {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    cartItems.value = []
    return
  }
  axios.post('/cart/list', {}, {
    headers: {
      token,
      Authorization: `Bearer ${token}`
    }
  }).then(res => {
    if(res.code == 200){
      cartItems.value = res.data; // 关键：赋值
      ElMessage.success('已获取购物车列表')
    }else {
      ElMessage.error(res.data.msg || '获取购物车列表失败')
    }
  })
}


const totalPrice = computed(() => {
  // 只统计待支付订单的总价
  return pendingCartItems.value.reduce((sum, item) => sum + (item.unitPrice * item.quantity), 0).toFixed(2)
})

function updateTotal(val, item) {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    return
  }
  axios.post(`/cart/update/${item.id}`, {
    quantity: item.quantity
  }, {
    headers: {
      token,
      Authorization: `Bearer ${token}`
    }
  }).then(res => {
    const data = res && res.data ? res.data : {}
    if (res.code == 200) {
      ElMessage.success('数量已更新')
    } else {
      ElMessage.error(data.msg || '更新败')
    }
  }).catch(e => {
    ElMessage.error('更新失败')
    console.error('updateTotal error:', e)
  })
}

function removeItem(index) {
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    return
  }
  const cartItem = cartItems.value[index]
  axios.post(`/cart/remove/${cartItem.id}`, {}, {
    headers: {
      token,
      Authorization: `Bearer ${token}`
    }
  }).then(res => {
    const data = res && res.data ? res.data : {}
    if (res.code == 200) {
      cartItems.value.splice(index, 1)
      ElMessage.success('已移除商品')
    } else {
      ElMessage.error(data.msg || '删除失败')
    }
  }).catch(e => {
    ElMessage.error('删除失败')
    console.error('removeItem error:', e)
  })
}

function checkout() {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }
  showDialog.value = true
}

function confirmOrder() {
  showDialog.value = false
  const token = sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    return
  }
  const cartItemIds = pendingCartItems.value.map(item => item.id)
  const orderData = {
    cartItemIds,
    totalAmount: totalPrice.value
  }
  axios.post('/cart/addOrder', orderData, {
    headers: {
      'Content-Type': 'application/json',
      token,
      Authorization: `Bearer ${token}`
    }
  }).then(res => {
    //console.log('后端返回:', res);
    console.log('res:', res);
    console.log('res.code:', res.code);
   console.log('res.data:', res.data);
   console.log('res.data.length:', res.data && res.data.length);
    if (res.code == 200 && res.data && res.data.length > 0) {
      const firstOrder = res.data[0];
      ElNotification.success({
        title: '成功',
        message: `\n  您的订单号为:${firstOrder.orderId || firstOrder.id}\n  付款金额:${firstOrder.totalAmount || totalPrice.value}\n`,
        duration: 3000
      });
      // 自动调用后端支付接口，弹出支付宝支付页面
      // axios.post('/cart/pay', null, {
      //   params: {
      //     orderId: firstOrder.orderId || firstOrder.id,
      //     money: firstOrder.totalAmount || totalPrice.value
      //   }
      // }).then(payRes => {
      //   console.log('payRes:', payRes);
      //   // 取出支付链接
      //   const payUrl = payRes.data ? payRes.data.data : payRes.data;
      //   // 新窗口打开支付链接
      //   window.open(payUrl, '_blank');
      // });
      axios.post(`/cart/pay?orderId=${firstOrder.orderId}&money=${firstOrder.totalAmount}`).then(res=>{
        window.open(res.data,'_blank','width=600,height=600')
      })
      cartItems.value = [] // 结算后清空，totalPrice 自动变 0
    } else {
      ElMessage.error(res.msg || '下单失败');
    }

  }).catch(e => {
    ElMessage.error('下单失败')
    console.error('confirmOrder error:', e)
  })

}
</script>

<style scoped>
.cart-page {
  max-width: 900px;
  margin: 0 auto;
  padding: 32px 16px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 16px rgba(0,0,0,0.06);
}
.cart-title {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 24px;
  color: #222;
  text-align: center;
}
.cart-empty {
  color: #aaa;
  text-align: center;
  font-size: 1.2rem;
  margin: 60px 0;
}
.cart-table {
  margin-bottom: 24px;
}
.cart-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  background: #f5f5f5;
}
.cart-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 32px;
  margin-top: 18px;
}
.cart-total {
  font-size: 1.3rem;
  font-weight: bold;
  color: #fa541c;
}
.cart-total span {
  font-size: 1.6rem;
  color: #fa541c;
}
.checkout-btn {
  font-size: 1.1rem;
  font-weight: bold;
  border-radius: 10px;
  padding: 0 32px;
}
</style> 